package com.pisolution.actuator.client.metrics;

import org.springframework.boot.actuate.endpoint.web.annotation.RestControllerEndpoint;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用于服务端索取垃圾回收器相关监控信息.
 *
 * @author sora
 * @version 0.1.0
 */
@SuppressWarnings("unused")
@RestControllerEndpoint(id = "gc-metric")
public class JVMMetricEndpoint {
    // -------------------------------------------------------------------------------------------------
    //  垃圾回收器监控信息索取
    // -------------------------------------------------------------------------------------------------

    /**
     * 获取垃圾回收器相关监控信息.
     *
     * @return 垃圾回收器运行数据.
     */
    @RequestMapping(method = RequestMethod.GET)
    public Map<String, Long> retrieve() {
        // 1. 获取虚拟机信息.
        final List<GarbageCollectorMXBean> beans = ManagementFactory.getGarbageCollectorMXBeans();

        // 2. 构建返回收据.
        final Map<String, Long> metrics = new HashMap<>();

        for (GarbageCollectorMXBean bean: beans) {
            metrics.put(bean.getName(), bean.getCollectionCount());
        }

        return metrics;
    }
}
